<?php
/*
 *      langugage.class.php
 *
 *      Copyright 2010 Patrice Ferlet <metal3d@gmail.com>
 *
 *      This program is free software; you can redistribute it and/or modify
 *      it under the terms of the GNU General Public License as published by
 *      the Free Software Foundation; either version 2 of the License, or
 *      (at your option) any later version.
 *
 *      This program is distributed in the hope that it will be useful,
 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *      GNU General Public License for more details.
 *
 *      You should have received a copy of the GNU General Public License
 *      along with this program; if not, write to the Free Software
 *      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 *      MA 02110-1301, USA.
 */

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com


// $Id: language.class.php 19 2010-12-14 22:46:23Z Metal3d $
// $HeadURL: http://valaya.googlecode.com/svn/trunk/utils/language.class.php $

class Language{
	private static $language = null;

	public static function get(){
		new Language;
		return self::$language;
	}
	public static function getBestMatch($langs = array()){
		foreach($langs as $n => $v)
		$langs[$n] = strtolower($v);
		$r = array();
		foreach(self::get() as $l => $v){
			($s = strtok($l, '-')) != $l && $r[$s] = 0;
			if(in_array($l, $langs))
			return $l;
		}
		foreach($r as $l => $v)
		if(in_array($l, $langs))
		return $l;
		return null;
	}
	private function __construct(){
		if(self::$language !== null)
		return;
		if(($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))){
			if(preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)){
				self::$language = array_combine($list[1], $list[2]);
				foreach(self::$language as $n => $v)
				self::$language[$n] = +$v ? +$v : 1;
				arsort(self::$language);
			}
		}
		else
		self::$language = array();
	}
}
